//
//  TotalScrollViewController.m
//  OpenYourEyes
//
//  Created by zhanglei on 15/8/10.
//  Copyright (c) 2015年 zhanglei. All rights reserved.
//

#define SIMPLE_SAMPLE NO

#import "TotalScrollViewController.h"
#import "Header.h"
#import "BaseButtonVIew.h"
#import "BTGlassScrollView.h"
#import "DownSideView.h"
#import "TotalFiveScrollView.h"
#import "MuchScrollView.h"
#import "MoviePlayerViewController.h"
#import "DoSomeGIF.h"
#import "VideoPlayerViewController.h"
#import "FMDatabase.h"
#import "AFNetworking.h"

@interface TotalScrollViewController ()
//上半部分scrollview
@property (nonatomic,strong)TotalFiveScrollView *viewScroll;
//下半部分的view
@property (nonatomic,strong)DownSideView *downsideView;
//底部页码的view
@property (nonatomic,strong)UIView* scrollFootView;
//底部页码显示的label
@property (nonatomic,strong)UILabel *pageNumberLabel;
//底部页码下面的白线
@property (nonatomic,strong)UIImageView *pageNumberWhiteLine;
//记录当前页面页码的属性
@property (nonatomic,assign)NSInteger page;
//给scrollview的图片一个button用来跳转播放
@property (nonatomic,strong)UIButton *centerButton;
//控制播放键透明度的大小
@property (nonatomic,assign)CGFloat imageAlphaCount;
//当前页面x在scrollview中的坐标
@property (nonatomic,assign)CGFloat contentOffsetX;
//滑动开始时的x坐标
@property (nonatomic,assign)CGFloat startContentOffsetX;
//滑动将要结束时的x坐标
@property (nonatomic,assign)CGFloat willEndContentOffsetX;
//滑动结束时的x坐标
@property (nonatomic,assign)CGFloat endContentOffsetX;
//记录并能更改当前视频是数据中第几天的属性
@property (nonatomic,assign)NSUInteger magicNum;
//一个时间控制器
@property (nonatomic,weak)NSTimer *myTimer;
//  数据库表
@property (nonatomic, strong)FMDatabase *db;
//收藏按钮
@property (nonatomic, strong)UIButton *collectionButton;
//收藏label
@property (nonatomic, strong)UILabel *collectionLabel;
//缓存下载按钮
@property (nonatomic, strong)UIButton *playButton;
//缓存下载Label
@property (nonatomic, strong)UILabel *playLabel;
//判断收藏状态
@property (nonatomic, strong)NSString *tureTitle;

@property (nonatomic, strong)NSURLRequest * request;

@property (nonatomic, strong)AFHTTPRequestOperation *operation;

@property (nonatomic, strong) NSMutableArray * dataArray;

@property (nonatomic, assign) BOOL isCollect;  //  判断是否收藏

@property (nonatomic, strong) UIButton *btnDownload;
//菊花控件
@property (nonatomic, strong)MBProgressHUD *testHUD;
//当前缓存视频的百分比
@property (nonatomic, strong)NSString *  value;

@end

@implementation TotalScrollViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}
//懒加载
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        self.dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //将天数控制参数置为0
    _magicNum = 0;
    //创建视图上得view
    [self createTheView];
    [self isCollection];
}

-(void)viewWillAppear:(BOOL)animated
{
    //开启定时器
    [_myTimer setFireDate:[NSDate distantPast]];
}
//封装视图上所有view的创建方法
- (void)createTheView
{
    //下半部分的视图
    [self createFirstView];
    //并且开启打印字特效
    [_downsideView startOutPut];
    //上半部分的scrollview
    [self createScrollView];
    //底部控制页码的视图
    [self createFootPageView];
    //为了防止第一张没有title所以在这里需要先获取一次model
    _model = _dataSource[_day + _magicNum][_idx];
    //navi的title
    self.navigationItem.title = _model.title;
    //scrollview中间的播放button以及其他视图
    [self AndCreateOtherViews];
    //判断当前是否被收藏
    [self isCollection];
    //添加两个按钮(收藏与下载)
    [self createTwoButton];
    //判断当前是否被下载
    [self isDownload];
    //下方收藏按钮的数据
    NSString *collection = [_model.consumption[@"shareCount"] stringValue];
    NSString *collectionNew = [NSString stringWithFormat:@"收藏:%@",collection];
    _collectionLabel.text = [NSString stringWithFormat:@"%@",collectionNew];
    //关闭菊花
    [_testHUD hide:YES];
    
}
//添加两个按钮(收藏与下载)
- (void)createTwoButton
{
    //为了自适应所以取一个会根据屏幕宽度不同而不同的值
    CGFloat ten = SCREEN_WIDTH / 48;
    //创建收藏按钮
    _collectionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _collectionButton.frame = CGRectMake(10, SCREEN_HEIGHT - 22 * ten, 3 * ten, 3 * ten);
    [_collectionButton setImage:[UIImage imageNamed:@"iconfont-weishoucang"] forState:UIControlStateNormal];
    _collectionButton.backgroundColor = [UIColor clearColor];
    [_collectionButton addTarget:self action:@selector(aaa) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_collectionButton];
    //创建收藏按钮旁的Label
    _collectionLabel = [[UILabel alloc]initWithFrame:CGRectMake(5 * ten + 5, SCREEN_HEIGHT - 22 * ten, 15 *ten, 3*ten)];
    _collectionLabel.font = [UIFont systemFontOfSize:14 weight:1];
    _collectionLabel.textColor = [UIColor colorWithWhite:0.900 alpha:1.000];
    [self.view addSubview:_collectionLabel];
    //创建缓存按钮
    _playButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _playButton.frame = CGRectMake(25 * ten, SCREEN_HEIGHT - 22 * ten, 13 * ten, 3 * ten);
    _playButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_playButton setTintColor:[UIColor whiteColor]];
    [_playButton addTarget:self action:@selector(bbb:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playButton];
    //创建缓存按钮
    _btnDownload = [UIButton buttonWithType:UIButtonTypeSystem];
    _btnDownload.frame = CGRectMake(24 * ten - 10, SCREEN_HEIGHT - 22 * ten, 3 * ten, 3 * ten);
    [_btnDownload setBackgroundImage:[UIImage imageNamed:@"iconfont-download"] forState:UIControlStateNormal];
    [_btnDownload addTarget:self action:@selector(bbb:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnDownload];
    //创建显示缓存进度的Label
    _playLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_playButton.frame) , SCREEN_HEIGHT - 22 * ten, 15 *ten, 3 * ten)];
    _playLabel.alpha = 0;
    _playLabel.textColor = [UIColor colorWithWhite:0.900 alpha:1.000];
    _playLabel.font = [UIFont systemFontOfSize:14 weight:1];
    [self.view addSubview:_playLabel];
}
//其他一些东西的创建
- (void)AndCreateOtherViews
{
    if (!SIMPLE_SAMPLE)
    {
        //创建5个scrollView
        [_viewScroll setFiveScrollView];
        //创建scrollView中心的Button
        _centerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _centerButton.frame = CGRectMake(SCREEN_WIDTH / 2 - 25 ,SCREEN_WIDTH / 2 - 50 , 50  , 50);
        _centerButton.userInteractionEnabled = NO;
        [_centerButton setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [self.view addSubview:_centerButton];
        //根据当前下标显示对应的页面
        [_viewScroll.viewScroller setContentOffset:CGPointMake(_idx * _viewScroll.viewScroller.frame.size.width, _viewScroll.viewScroller.contentOffset.y)];
    }
}

- (void)aaa
{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Collection.db"];
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open]) {
        NSLog(@"数据库打开失败");
        return;
    }
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS Collection (Category text, CoverBlurred text, CoverForDetail text, CoverForFeed text, CoverForSharing text, Date integer, Description text, Duration integer, ID integer,Idx integer, PlayUrl text, RawWebUrl text, Title text, WebUrl text)"];
    
    // 在存储之前先进行一次判断 如果数据库已经存储了 就不走下列方法
    //  查询数据库
    if (_isCollect == YES)
    {
        [self delete_modelFromDatabase];
        [_collectionButton setImage:[UIImage imageNamed:@"iconfont-weishoucang"] forState:UIControlStateNormal];
        
        int a =  [_model.consumption[@"shareCount"] intValue];
        NSNumber *b = [NSNumber numberWithInt:a];
        NSString *collection = [b stringValue];
        NSString *collectionNew = [NSString stringWithFormat:@"收藏:%@",collection];
        _collectionLabel.text = [NSString stringWithFormat:@"%@",collectionNew];
        
        _isCollect = NO;
        
    } else
    {
        [self make_modelToDatabase];
        [_collectionButton setImage:[UIImage imageNamed:@"yishoucang"] forState:UIControlStateNormal];
        
        int a =  [_model.consumption[@"shareCount"] intValue] + 1;
        NSNumber *b = [NSNumber numberWithInt:a];
        NSString *collection = [b stringValue];
        NSString *collectionNew = [NSString stringWithFormat:@"收藏:%@",collection];
        _collectionLabel.text = [NSString stringWithFormat:@"%@",collectionNew];

        _isCollect = YES;
    }
}

#pragma park - 将_model存储到数据库中
- (void)make_modelToDatabase
{
    NSNumber *duration = [NSNumber numberWithInteger:_model.duration];
    NSNumber *ID = [NSNumber numberWithInteger:_model.ID];
    NSNumber *idx = [NSNumber numberWithInteger:_model.idx];
    NSNumber *date = [NSNumber numberWithInteger:_model.date];
    
    [_db executeUpdate:@"INSERT INTO Collection (Category, CoverBlurred,CoverForDetail,CoverForFeed,CoverForSharing,Date,Description,Duration,ID,Idx,PlayUrl,RawWebUrl,Title,WebUrl) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",_model.category,_model.coverBlurred,_model.coverForDetail,_model.coverForFeed,_model.coverForSharing,date,_model.Description,duration,ID,idx,_model.playUrl,_model.rawWebUrl,_model.title,_model.webUrl];
}

#pragma park - 将_model存储到缓存数据库中
- (void)make_modelToDownloadDatabase
{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Collection.db"];
    NSLog(@"%@",path);
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open]) {
        NSLog(@"数据库打开失败");
        return;
    }
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS Download (Category text, CoverBlurred text, CoverForDetail text, CoverForFeed text, CoverForSharing text, Date integer, Description text, Duration integer, ID integer,Idx integer, PlayUrl text, RawWebUrl text, Title text, WebUrl text)"];
    NSNumber *duration = [NSNumber numberWithInteger:_model.duration];
    NSNumber *ID = [NSNumber numberWithInteger:_model.ID];
    NSNumber *idx = [NSNumber numberWithInteger:_model.idx];
    NSNumber *date = [NSNumber numberWithInteger:_model.date];
    
    [_db executeUpdate:@"INSERT INTO Download (Category, CoverBlurred,CoverForDetail,CoverForFeed,CoverForSharing,Date,Description,Duration,ID,Idx,PlayUrl,RawWebUrl,Title,WebUrl) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",_model.category,_model.coverBlurred,_model.coverForDetail,_model.coverForFeed,_model.coverForSharing,date,_model.Description,duration,ID,idx,_model.playUrl,_model.rawWebUrl,_model.title,_model.webUrl];
}

- (void)bbb:(UIButton *)btn
{
    
    _playLabel.alpha = 1;
    if ([_playButton.currentTitle isEqualToString:@"缓存"])
    {
        [_playButton setTitle:@"取消缓存" forState:UIControlStateNormal];
                NSURL * url = [NSURL URLWithString:_model.playUrl];
        self.request = [NSURLRequest requestWithURL:url];
        unsigned long long  downloadedBytes = 0;
        
        //如果存在,说明有缓存文件
        if ([[NSFileManager defaultManager] fileExistsAtPath:[self IsExistFilePath]])
        {
            //计算缓存文件的大小
            downloadedBytes = [self fileSizeAtPath:[self IsExistFilePath]];
            NSMutableURLRequest * mutableURLRequest = [_request mutableCopy];
            NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];
            [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];
            _request = mutableURLRequest;
        }
        [[NSURLCache sharedURLCache] removeCachedResponseForRequest:_request];
        _operation = [[AFHTTPRequestOperation alloc] initWithRequest:_request] ;
        __block typeof(_operation)myOperation = _operation;
        [_operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:[self IsExistFilePath] append:YES]];
        [myOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

            //显示下载百分比
//<<<<<<< HEAD
//            CGFloat present = (CGFloat)(totalBytesRead +downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes) ;
//            _value = [NSString stringWithFormat:@"%.f%%", present * 100];
//            NSLog(@"已缓存:%@",_value);
//=======
////            CGFloat present = (CGFloat)(totalBytesRead +downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes) ;
////            _value = [NSString stringWithFormat:@"%.f%%", present * 100];
////            self.playLabel.text = _value;
//>>>>>>> 5ca72981a391c7aa0e75b254a525569503ab9beb
        }];
        
        //下载成功的回调
        [myOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
        {
            NSString * str = [NSString stringWithFormat:@"<<%@>>已缓存完成",_model.title];
            //下载成功的提示框
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:str  delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
            [_playButton setTitle:@"已缓存" forState:UIControlStateNormal];
            [[NSFileManager defaultManager] moveItemAtPath:[self IsExistFilePath] toPath:[self IsExistdownLoadFilePath] error:nil];
            
            _playButton.userInteractionEnabled = NO;
            _playButton.alpha = 0.6;
            _btnDownload.userInteractionEnabled = NO;
            _btnDownload.alpha = 0.4;
            _playLabel.text = @"";

            [self.dataArray addObject:_model];
            
            FMResultSet *rs = [_db executeQuery:@"SELECT * FROM Collection where title = ?",_model.title];
            while ([rs next])
            {
                return;
            }
            //  将缓存好的信息  存在数据库
            [self make_modelToDownloadDatabase];
            
            

        } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        }];
        //开启任务, 必须是手动开启
        [_operation start];
    }
    
    else{
        [_playButton setTitle:@"缓存" forState:UIControlStateNormal];
        [_operation cancel];
        _operation = nil;
        [self deleteFileAtPath:_model.title];
        _playLabel.alpha = 0;
    }
}

#pragma park - 判断是否下载到本地
- (void)isDownload
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:[self IsExistdownLoadFilePath]])
    { //  如果本地存在,目的是让下载按钮变成灰色,无法点击
        
            [_playButton setTitle:@"已缓存" forState:UIControlStateNormal];
            _playButton.userInteractionEnabled = NO;
            _playButton.alpha = 0.6;
            _btnDownload.userInteractionEnabled = NO;
            _btnDownload.alpha = 0.4;
    }
    else
    {
        if([fileManager fileExistsAtPath:[self IsExistFilePath]])
        {
            [_playButton setTitle:@"取消缓存" forState:UIControlStateNormal];
            _btnDownload.userInteractionEnabled = YES;
            _btnDownload.alpha = 1;
            _playButton.userInteractionEnabled = YES;
            _playButton.alpha = 1;
        }else{
        [_playButton setTitle:@"缓存" forState:UIControlStateNormal];
        _btnDownload.userInteractionEnabled = YES;
        _btnDownload.alpha = 1;
        _playButton.userInteractionEnabled = YES;
        _playButton.alpha = 1;
        }
    }
}


//下载路径
- (NSString *)IsExistFilePath
{
    _model = _dataSource[_day + _magicNum][_idx];
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
    
    NSString * filePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",_model.title]];
    NSLog(@"-----------%@",_model.title);
    return filePath;
}

//下载完成的路径
- (NSString *)IsExistdownLoadFilePath
{
    _model = _dataSource[_day + _magicNum][_idx];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    NSString * tmp = [NSHomeDirectory() stringByAppendingString:@"/tmp"];
    
    NSString * _modelPath = [tmp stringByAppendingString:@"/_model"];
    if (![fileManager fileExistsAtPath:_modelPath]) {
        [fileManager createDirectoryAtPath:_modelPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString * downLoadFinished = [_modelPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",_model.title]];
    return downLoadFinished;
}
//计算缓存路径的大小
- (unsigned long long)fileSizeAtPath:(NSString *)fileAbsolutePath
{
    signed long long fileSize = 0;
    NSFileManager * fileManager = [NSFileManager new];
    if ([fileManager fileExistsAtPath:fileAbsolutePath]) {
        NSError *error = nil;
        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:fileAbsolutePath error:&error];
        if (!error && fileDict) {
            fileSize = [fileDict fileSize];
        }
    }
    return fileSize;
}

#pragma
- (void)isCollection
{
    _model = _dataSource[_day + _magicNum][_idx];
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Collection.db"];
    NSLog(@"%@",path);
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open]) {
        NSLog(@"数据库打开失败");
        return;
    }

    //  查询数据库
    FMResultSet *rs = [_db executeQuery:@"SELECT * FROM Collection where title = ?",_model.title];
    while ([rs next])  //  类库中的方法  循环查询
    {
        [_collectionButton setImage:[UIImage imageNamed:@"yishoucang"] forState:UIControlStateNormal];
        _isCollect = YES;
        return;
    }
    _isCollect = NO;
    
    [_collectionButton setImage:[UIImage imageNamed:@"iconfont-weishoucang"] forState:UIControlStateNormal];
    
}


#pragma park - 将_model从数据库删除
- (void)delete_modelFromDatabase
{
    //  按title 查询删除
    NSString *str = _model.title;
    //  删除数据库的方法
    NSString *deleteStr = [NSString stringWithFormat:@"DELETE fROM %@ where %@ = '%@'",@"Collection",@"Title",str];
    [_db executeUpdate:deleteStr];
}

#pragma park - 删除本地正在缓存的视频
- (void)deleteFileAtPath:(NSString *)filename {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * tmp = [NSHomeDirectory() stringByAppendingString:@"/Library"];
    NSString * _modelPath = [tmp stringByAppendingString:@"/Caches"];
    NSString *delelteFilePath = [_modelPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",filename]];
    [fileManager removeItemAtPath:delelteFilePath error:nil];
}

- (void)collectThe_model
{
    NSLog(@"111");
}

//创建底部可滑动的页码视图
- (void)createFootPageView
{
    _scrollFootView = [[UIView alloc]initWithFrame:CGRectMake(_idx * SCREEN_WIDTH / 5, SCREEN_HEIGHT - 90, SCREEN_WIDTH / 5, 30)];
    
    _pageNumberLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 5, 28)];
    _pageNumberLabel.textColor = [UIColor colorWithWhite:0.900 alpha:1.000];
    _pageNumberLabel.font = [UIFont fontWithName:@"TimesNewRomanPS-ItalicMT" size:15];
    CGFloat num = 5;
    _pageNumberLabel.text = [NSString stringWithFormat:@"%ld / %d",(long)_idx + 1,(int)num];
    _pageNumberLabel.textAlignment = NSTextAlignmentCenter;
    
    _pageNumberWhiteLine = [[UIImageView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 120, SCREEN_WIDTH / 5, 2)];
    _pageNumberWhiteLine.backgroundColor = [UIColor whiteColor];
    
    [_scrollFootView addSubview:_pageNumberLabel];
    [_scrollFootView addSubview:_pageNumberWhiteLine];
    
    [self.view addSubview:_scrollFootView];
}

//创建scrollview
- (void)createScrollView
{
    _viewScroll = [[TotalFiveScrollView alloc]initWithFrame:CGRectMake(0 ,0, self.view.frame.size.width, self.view.frame.size.height)];
    
    _viewScroll.section = _dataSource[_day + _magicNum];
    
    _viewScroll.idx = _idx;
    
    _viewScroll.viewScroller.delegate = self;
    
    //为每张视图添加点击手势
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    UITapGestureRecognizer *tap5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    
    [_viewScroll.scrollView1 addGestureRecognizer:tap1];
    [_viewScroll.scrollView2 addGestureRecognizer:tap2];
    [_viewScroll.scrollView3 addGestureRecognizer:tap3];
    [_viewScroll.scrollView4 addGestureRecognizer:tap4];
    [_viewScroll.scrollView5 addGestureRecognizer:tap5];

    [self.view addSubview:_viewScroll];
}

//点击事件实现
- (void)tapAction:(UIGestureRecognizer *)sender
{
    NSLog(@"点击跳转播放");
    
    VideoPlayerViewController *_modelVC = [[VideoPlayerViewController alloc] init];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self IsExistdownLoadFilePath]])
    {
        NSURL *url = [NSURL fileURLWithPath:[self IsExistdownLoadFilePath]];
        _modelVC.url = url;
    } else
    {
        _model = _dataSource[_day + _magicNum][_idx];
        _modelVC.url = [NSURL URLWithString:_model.playUrl];
    }

    _modelVC.model = _model;
    
    _modelVC.myblock = ^void(){
        [self bbb:_btnDownload];
    };
    
    [self presentViewController:_modelVC animated:YES completion:nil];
}






//下面的视图创建
- (void)createFirstView
{
    _downsideView = [[DownSideView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT / 2, SCREEN_WIDTH, SCREEN_HEIGHT / 2)];
    
    //判断,如果当前是数据获取到的最后一天时
    if((_day +_magicNum) >= 5)
    {
        _magicNum = 0;
        _downsideView.section = _dataSource[_day + _magicNum];
    }else
    {
        _downsideView.section = _dataSource[_day + _magicNum];
    }
    
    _downsideView.idx = _idx;
    
    _downsideView.model = _downsideView.section[_idx];
    
    _downsideView.firstView.alpha = 1;
    
    [self.view addSubview:_downsideView];
}

//滑动过程中
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat ratio = scrollView.contentOffset.x / scrollView.frame.size.width;
    //更改记录page页码的属性
    _page = (int)floor(ratio);
    
    _idx = _page;
    if (ratio > -1 && ratio < 1) {
        [_viewScroll.scrollView1 scrollHorizontalRatio:-ratio];
    }
    if (ratio > 0 && ratio < 2) {
        [_viewScroll.scrollView2 scrollHorizontalRatio:-ratio + 1];
    }
    if (ratio > 1 && ratio < 3) {
        [_viewScroll.scrollView3 scrollHorizontalRatio:-ratio + 2];
    }
    if (ratio > 2 && ratio < 4) {
        [_viewScroll.scrollView4 scrollHorizontalRatio:-ratio + 3];
    }
    if (ratio > 3 && ratio < 5) {
        [_viewScroll.scrollView5 scrollHorizontalRatio:-ratio + 4];
    }
    //更改中间播放button的透明度
    CGFloat num1 = ratio - _page;
    
    if (num1 < 0.5) {
        _imageAlphaCount = 1 - num1 * 2;
    }else
    {
        _imageAlphaCount = (num1 - 0.5) * 2;
    }
    _centerButton.imageView.alpha = _imageAlphaCount;
    //
    _contentOffsetX = scrollView.contentOffset.x;

    //更改底部页码位置
    _scrollFootView.frame = CGRectMake(ratio * SCREEN_WIDTH / 5, SCREEN_HEIGHT - 90, SCREEN_WIDTH / 5, 30);
}

//本来是用来控制下半部分跟随滑动改变透明度的,不过暂时弃用了.
- (void)howMuchTheAlphaChanged
{
    CGFloat num2 =  _contentOffsetX - _startContentOffsetX;
    if (num2 > 0)
    {
        _downsideView.firstView.alpha = (SCREEN_WIDTH - num2)/SCREEN_WIDTH + 0.03;
    }
    else if(num2 < 0)
    {
        _downsideView.firstView.alpha = (SCREEN_WIDTH + num2)/SCREEN_WIDTH + 0.03;
    }
    else if (num2 == SCREEN_WIDTH || num2 == 0)
    {
        _downsideView.firstView.alpha = 1.0;
    }
}
//当滑动开始时
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{    //获取拖动前的起始坐标
    _startContentOffsetX = _viewScroll.viewScroller.contentOffset.x;
    
}
//滑动将要结束时
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    //将要停止前的坐标
    _willEndContentOffsetX = scrollView.contentOffset.x;
}

//定时器的执行方法
- (void)scrollTimer
{
    [self changeTheScrollView];
}

- (void)scrollTimer2
{
    [self ToTheBeforeScrollView];
}
//当滑动结束时
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _model = _dataSource [_magicNum + _day][_page];

    if ( _willEndContentOffsetX < _startContentOffsetX)
    {
        //画面从右往左移动，前一页
        if(_startContentOffsetX == 0)
        {
            //添加菊花
            [self createActivityIndicator];
            //关闭交互
            _viewScroll.userInteractionEnabled = NO;
            //执行定时器
            _myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scrollTimer2) userInfo:nil repeats:NO];
        }
        
    }
    else if ( _willEndContentOffsetX > _startContentOffsetX)
    {    //画面从左往右移动，后一页
        //如果起始坐标是第五页
        if (_startContentOffsetX == 4 * SCREEN_WIDTH)
        {
            //添加菊花
            [self createActivityIndicator];
            //关闭交互
            _viewScroll.userInteractionEnabled = NO;
            //执行定时器
            _myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scrollTimer) userInfo:nil repeats:NO];
        }
    }
    //更改navi的title
    self.navigationItem.title = _model.title;
    //当前页的_model根据页数变化而变化
    _downsideView.model = _model;
    //拖拽完毕后-->打字机效果
    [_downsideView startOutPut];
    //更改下方页码
    NSUInteger num = 5;
    _pageNumberLabel.text = _pageNumberLabel.text = [NSString stringWithFormat:@"%d / %lu",_page + 1,(unsigned long)num];
    
    NSString *collection = [_model.consumption[@"shareCount"] stringValue];
    NSString *collectionNew = [NSString stringWithFormat:@"收藏:%@",collection];
    _collectionLabel.text = [NSString stringWithFormat:@"%@",collectionNew];

    [self isCollection];
    [self isDownload];
}

//下一次5个视频加载使用的方法
- (void)changeTheScrollView
{
    //当处于最后一页时
        if ((_day + _magicNum)< 5)
        {
            //将页码置为第一页
            _idx = 0;
            //天数加1
            _magicNum++;
            //加载视图
            [self loadView];
            //创建视图上得这些view
            [self createTheView];
        }
}
//上一个5个视频加载使用的方法
- (void)ToTheBeforeScrollView
{
    if ((_day + _magicNum) > 0)
    {
        _idx = 4;
        _magicNum -- ;
        [self loadView];
        [self createTheView];
    }
    else if(_day == 0)
    {
        _viewScroll.userInteractionEnabled = YES;
        //关闭菊花
        [_testHUD hide:YES];
        UIAlertView *message = [[UIAlertView alloc]initWithTitle:@"呵呵" message:@"已经到第一页啦,没有更多的了." delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [message show];
    }
}
//播放一个菊花
- (void)createActivityIndicator
{
    _testHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //如果设置此属性则当前的view置于后台
    _testHUD.dimBackground = YES;
    //设置对话框文字
    _testHUD.labelText = @"请稍等";
}


@end
